package com.st.buy.search.controller;

import com.st.buy.search.service.SearchService;
import com.st.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author 张双虎
 */
@Controller
public class SearchController {

    @Autowired
    private SearchService searchService;

    @RequestMapping("/search/importIndex")
    @ResponseBody
    public BuyResult importIndex(){
        return searchService.importIndex();
    }

    @RequestMapping("/search")
    public String search(String keyword, @RequestParam(defaultValue = "1")int page, @RequestParam(defaultValue = "60") int rows, Model model){
        Map result = searchService.query(keyword,page,rows);
        model.addAttribute("itemList",result.get("searchItems"));
        // 将查询关键在放在request的作用域
        model.addAttribute("query",keyword);
        //当前页码
        model.addAttribute("page",page);
        //总条数recourdCount
        Object count = result.get("recourdCount");
        long recourdCount = count!=null && !"".equals(count)?new Long(count.toString().trim()):0;
        model.addAttribute("recourdCount",recourdCount);
        //最大页码totalPages
        //计算最大页码
        model.addAttribute("totalPages",(int)(Math.ceil(recourdCount*1.0/rows)));
        return "search";
    }

}
